import json
import urllib.request
import urllib.parse
import re
from cons import stations
import xlwt
date = input('请输入时间格式为：2018-01-11：')
from_=stations[input('请输入发车城市')]
to_= stations[input('请输入目的城市')]
# date = '2018-01-11'
# from_=stations['北京']
# to_= stations['定州']
print(from_,to_)
url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date='+date+'&leftTicketDTO.from_station='+from_+'&leftTicketDTO.to_station='+to_+'&purpose_codes=ADULT'
print(url)
# req = urllib.request.Request(url)
# req. add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36')

html = urllib.request.urlopen(url).read()
json_list = json.loads(html)['data']['result']

workbook = xlwt.Workbook(encoding='utf-8')

sheet1  = workbook.add_sheet(date)
sheet1.write(0,0,'车次')
sheet1.write(0,1,"发车时间")
sheet1.write(0,2,"到达时间")
sheet1.write(0,3,"耗时")
count = 0
for i in json_list:
    count +=1
    n = i.split("|")
    sheet1.write(count,0,str(n[3]))
    sheet1.write(count,1,str(n[8]))
    sheet1.write(count,2,str(n[9]))
    sheet1.write(count,3,str(n[10]))
#     print('车次为：' + str(n[3]) + '出发时间：' + str(n[8]) + '到达时间：' + str(n[9]) + '运行时间：' + str(n[10]))
# 3 = 车次 8=出发时间 9=到达时间 10 = 运行时间
#  32商务  31一等 30二等 23软卧 27动卧 28硬卧 25软座 29硬座 26无座  22其他

workbook.save('1.xls')